<template>
  <div>
    <el-tag
      v-for="item in dynamicTags"
      :key="item"
      closable
      :disable-transitions="false"
      @close="handleClose"
    >
      {{ item }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="inputRef"
      v-model="inputValue"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    ></el-input>
    <el-button
      v-else
      class="button-new-tag ml-1"
      size="small"
      @click="showInput"
      >+ 添加</el-button 
    >
  </div>
</template>

<script setup>
import { nextTick, ref } from "vue";
const props = defineProps({
  modelValue: String,
});
const emit = defineEmits(["update:modelValue"]);
const inputValue = ref("");
// 接受父组件字符串转成数组
console.log(props.modelValue,"------");
const dynamicTags = ref(props.modelValue ? props.modelValue.split(",") : []);
const inputVisible = ref(false)
const inputRef = ref(null)
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag),1)
  // 传字符串
  emit('update:modelValue',dynamicTags.value.join(','))
}
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value.input.focus()
  })
}
const handleInputConfirm = () => {
  if(inputValue.value) {
    dynamicTags.value.push(inputValue.value)
    // 传字符串
    emit('update:modelValue',dynamicTags.value.join(','))
  }
  inputVisible.value = false
  inputValue.value = ''
}


</script>

<style lang="less" scoped></style>
